
package com.jf.cloud.search.controller.app;

import cn.hutool.core.collection.CollUtil;
import com.jf.cloud.api.dto.EsPageDTO;
import com.jf.cloud.api.product.feign.SpuFeignClient;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.product.constant.SupplierDeliveryType;
import com.jf.cloud.common.product.constant.SupplierSpuType;
import com.jf.cloud.common.product.dto.ProductSearchDTO;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.product.vo.search.ProductSearchVO;
import com.jf.cloud.common.product.vo.search.SpuAdminVO;
import com.jf.cloud.common.product.vo.search.SpuSearchVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.constant.EsConstant;
import com.jf.cloud.search.constant.EsRenovationProductSortEnum;
import com.jf.cloud.search.manager.ProductSearchManager;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品搜索
 * @author zz
 * @date 2020/11/16
 */
@RestController("appSearchSpuController")
@RequestMapping("/ua/search")
@Tag(name = "spu搜索接口")
public class ProductSearchController {

    @Autowired
    private ProductSearchManager productSearchManager;
    @Autowired
    private SpuFeignClient spuFeignClient;
    @Autowired
    private MapperFacade mapperFacade;


    @GetMapping("/pc_page")
    @Operation(summary = "pc端商品搜索接口" , description = "pc端商品搜索接口")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> pcPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setAttrMap(productSearchManager.splitAttr(productSearchDTO.getAttrIds()));
        productSearchDTO.setAppDisplay(true);
        productSearchDTO.setIsSupplierType(1);
        EsPageVO<ProductSearchVO> searchPage =  productSearchManager.page(pageDTO, productSearchDTO);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        ServerResponseEntity<List<ProductSearchVO>> listServerResponseEntity = spuFeignClient.usCheckCommissionSpuIsUpdateMsg(searchPage.getList());
        List<ProductSearchVO> result = listServerResponseEntity.getData();

        //仅看有货
        if(Objects.nonNull(productSearchDTO.getHasStock()) && Objects.equals(productSearchDTO.getHasStock(), 1)){
            //供应商发货的代销商品Spu
            List<SpuSearchVO> commissionList = searchPage.getList().get(0).getSpus().stream().filter(item -> Objects.equals(item.getSupplierSpuType(), SupplierSpuType.CONSIGNMENT.value()) && Objects.equals(item.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value())).collect(Collectors.toList());
            List<Long> commisionIds = commissionList.stream().map(SpuSearchVO::getSpuId).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(commisionIds)){
                List<SpuVO> spuIsSyn = spuFeignClient.getSpuIsSynUpdate(commisionIds).getData();
                Map<Long, Integer> stockInfo = spuIsSyn.stream().collect(Collectors.toMap(SpuVO::getSpuId, SpuVO::getTotalStock));
                List<Long> zeroStock = new ArrayList<>();
                for (Long spuId : commisionIds){
                    if(Objects.equals(stockInfo.get(spuId), 0)){
                        zeroStock.add(spuId);
                    }
                }
                //获取供应商发货的代销商品的id,过滤掉供应商库存为0的商品
                List<SpuSearchVO> searchList = result.get(0).getSpus().stream().filter(SpuSearch -> !zeroStock.contains(SpuSearch.getSpuId())).collect(Collectors.toList());
                result.get(0).setSpus(searchList);
            }

        }


        searchPage.setList(result);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/page")
    @Operation(summary = "商品搜索接口（仅商品信息）" , description = "商品搜索接口")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> page(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        return ServerResponseEntity.success(simplePage(pageDTO, productSearchDTO));
    }

    @GetMapping("/search_page")
    @Operation(summary = "手机端商品搜索接口" , description = "手机端商品搜索接口")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> searchPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setAttrMap(productSearchManager.splitAttr(productSearchDTO.getAttrIds()));
        EsPageVO<ProductSearchVO> page = simplePage(pageDTO, productSearchDTO);
        ProductSearchVO productSearchVO = page.getList().get(0);
        ProductSearchVO productInfo = productSearchManager.searchExtension(pageDTO, productSearchDTO);
        if (!Objects.isNull(productInfo.getAttrs())){
            productSearchManager.loadAttr(productInfo, null);
        }
        productSearchVO.setBrands(productInfo.getBrands());
        productSearchVO.setAttrs(productInfo.getAttrs());
        productSearchVO.setCategorys(productInfo.getCategorys());
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        ServerResponseEntity<List<ProductSearchVO>> listServerResponseEntity = spuFeignClient.usCheckCommissionSpuIsUpdateMsg(page.getList());
        List<ProductSearchVO> result = listServerResponseEntity.getData();
        page.setList(result);
        return ServerResponseEntity.success(page);
    }

    @GetMapping("/page_distribution_spu")
    @Operation(summary = "分销商品列表" , description = "分销商品列表")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> pageDistributionSpu(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setDistributionSpu(Boolean.TRUE);
        productSearchDTO.setFetchSource(EsConstant.DISTRIBUTION_SPU_SOURCE);
        EsPageVO<ProductSearchVO> searchPage = productSearchManager.page(pageDTO, productSearchDTO);
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/renovation_page")
    @Operation(summary = "商品信息列表(app装修商品列表)" , description = "商品信息列表(app装修商品列表)")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> renovationPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long size = null;
        if(Objects.equals(productSearchDTO.getShowSpuType(),1)){
            if(Objects.equals(productSearchDTO.getEsRenovationSpuSort(), EsRenovationProductSortEnum.CREATE_TIME_ASC.value()) || Objects.equals(productSearchDTO.getEsRenovationSpuSort(),EsRenovationProductSortEnum.CREATE_TIME_DESC.value())){
                productSearchDTO.setSort(productSearchDTO.getEsRenovationSpuSort());
            }else {
                // 获取指定规则的商品ids并返回大小
                size = getSpuIds(pageDTO, productSearchDTO);
            }
        }
        EsPageVO<ProductSearchVO> searchPage =  productSearchManager.renovationPage(pageDTO, productSearchDTO, size);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        return ServerResponseEntity.success(searchPage);
    }

    private Long getSpuIds(EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        Long shopId = Objects.isNull(productSearchDTO.getShopId()) ? 0L :  productSearchDTO.getShopId();
        String key = EsConstant.RENOVATION_PRODUCT_IDS_CACHE + CacheNames.UNION + shopId +
                CacheNames.UNION_KEY + productSearchDTO.getEsTimeRange() + CacheNames.UNION_KEY + productSearchDTO.getEsRenovationSpuSort()
                + CacheNames.UNION_KEY + productSearchDTO.getPrimaryCategoryId();
        if(!RedisUtil.hasKey(key)){
            productSearchManager.addRenovationSpuCache(key,productSearchDTO, shopId, EsConstant.RENOVATION_PRODUCT_IDS_CACHE_TIME);
//            return new ArrayList<>();
        }
        Long size = RedisUtil.getListSize(key);
        long startNum = (long) (pageDTO.getPageNum() - 1) * pageDTO.getPageSize();
        long endNum = (long) pageDTO.getPageNum() * pageDTO.getPageSize() - 1;
        endNum = Math.min(endNum,size - 1);
        List spuIds = RedisUtil.getListRange(key, startNum, endNum);
        productSearchDTO.setSpuIds(spuIds);
        // 从spuId获取应该每次都是第一页
        pageDTO.setPageNum(1);
        return size;
    }

    private EsPageVO<ProductSearchVO> simplePage(EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        EsPageVO<ProductSearchVO> searchPage =  productSearchManager.spuPage(pageDTO, productSearchDTO);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        //检查代销商品是否改变了原有得供应商图片和名字，如果改变了显示商家改变后的图片和名字，没有改变则显示供应商信息
        List<SpuSearchVO> spus = searchPage.getList().get(0).getSpus();
        List<SpuAdminVO> spuAdminList = mapperFacade.mapAsList(spus, SpuAdminVO.class);
        List<SpuAdminVO> data = spuFeignClient.checkCommissionSpuIsUpdateMsg(spuAdminList).getData();
        List<SpuSearchVO> spuSearchList = mapperFacade.mapAsList(data, SpuSearchVO.class);
        Map<Long, SpuSearchVO> spuMap = spus.stream().collect(Collectors.toMap(SpuSearchVO::getSpuId, s -> s));
        for (SpuSearchVO spuSearchVO : spuSearchList) {
            if (!spuMap.containsKey(spuSearchVO.getSpuId())) {
                continue;
            }
            SpuSearchVO spu = spuMap.get(spuSearchVO.getSpuId());
            spuSearchVO.setSpuActivity(spu.getSpuActivity());
        }

        searchPage.getList().get(0).setSpus(spuSearchList);
        return searchPage;
    }
}
